<template>
  <div class="part-batchIn-form">
    <el-table v-table-style :data="form" :empty-text="$t('part.text23')">
      <el-table-column :label="$t('common.base.name')" width="150px">
        <el-autocomplete
          slot-scope="scope"
          popper-class="batch-in-part"
          v-model="scope.row.sparepartName"
          :fetch-suggestions="fetchSparepart"
          :placeholder="$t('common.placeholder.inputContent')"
          @select="choosePart($event,scope.row)">

          <div class="bacth-in-part-item" slot-scope="scope">
            <p>{{ $t('common.base.name') }}：{{scope.item.sparepart&&scope.item.sparepart.name}}</p>
            <p>{{$t('common.label.serialNumber')}}：{{scope.item.sparepart&&scope.item.sparepart.serialNumber}}</p>
            <p>{{$t('common.part.specifications')}}：{{scope.item.sparepart&&scope.item.sparepart.standard}}</p>
            <div class="item-more">
              <div class="item-more-info"><p>{{$t('common.base.warehouse')}}：{{scope.item.repertory&&scope.item.repertory.name}}</p></div>
              <div v-if="!type && scope.item.showArrow" @click.stop="scope.item.showDetail = !scope.item.showDetail">
                <i v-show="!scope.item.showDetail" class="iconfont icon-fdn-select"></i>
                <i v-show="scope.item.showDetail" class="iconfont icon-Icon_up"></i>
              </div>
            </div>
            <!--是否显示剩余的字段-->
            <div v-if="!type && scope.item.showDetail">
              <p>{{$t('common.label.explain')}}：{{scope.item.sparepart&&scope.item.sparepart.description}}</p>
            </div>
            </div>
        </el-autocomplete>
      </el-table-column>
      <el-table-column :label="$t('common.label.serialNumber')" prop="serialNumber" width="150px" class-name="part-spares-serial-num"></el-table-column>
      <el-table-column :label="$t('common.part.specifications')" prop="sparepartType" width="100px"></el-table-column>
      <el-table-column :label="$t('common.label.sparepartStandard')" prop="standard" width="100px"></el-table-column>
      <el-table-column :label="$t('common.base.warehouse')" prop="repertory" width="100px"></el-table-column>
      <el-table-column :label="$t('common.label.type')" width="150px">
        <el-select v-model="scope.row.type" slot-scope="scope">
          <el-option v-for="option in sparepartConfig.outStoreType" :key="option" :label="option" :value="option"></el-option>
        </el-select>
      </el-table-column>
      <el-table-column :label="$t('part.field9')" prop="repertoryCount" width="150px">
        <template slot-scope="scope">
          {{scope.row.repertoryCount}}
          <el-tooltip class="item" effect="dark" :content="`${$t('part.text9')}：${scope.row.safetyStock}`" placement="top">
            <el-tag v-if="scope.row.safetyStock && (scope.row.safetyStock > scope.row.repertoryCount)" size="mini" type="danger">{{ $t('part.components.partStock.text2') }}</el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common.part.quantity')" width="80px">
        <el-input slot-scope="scope" v-model="scope.row.variation" type="number" step="any" :min="0" :max="parseInt(scope.row.repertoryCount)"></el-input>
      </el-table-column>
      <el-table-column :label="$t('common.label.operate')" width="60px" fixed="right">
        <el-button type="text" @click="remove(scope.row)" slot-scope="scope">{{ $t('common.base.delete') }}</el-button>
      </el-table-column>
    </el-table>

    <div class="out-stock-remark" v-if="form.length > 0">
      <el-input type='textarea' :maxlength="500" :placeholder="$t('common.base.tip.inputCommentContent')" v-model="remark"></el-input>
    </div>

    <div class="part-batchIn-footer">
      <el-button type="text" @click="add" icon="el-icon-plus">{{ $t('common.paas.buttons.add') }}</el-button>
    </div>
  </div>
</template>

<script>
import MathUtil from '@src/util/math';
import { t } from '@src/locales'
export default {
  name: 'part-outstock-batch-form',
  inject: ['initData'],
  props: {
    sparepartConfig: Object,
    repertoryId: '', // 仓库id
    type: String,
  },
  data(){
    return {
      userId: '',
      form: [],
      remark:'',
      partOptions: [],
      numberValidateForm: {
        number: ''
      },
      rules: {
        content: [
          {required: true, message: t('common.paas.view.template.detail.placeholder1')},
          {max: 500, message: t('part.components.partRemarkForm.text2', {max:500})}
        ],
        number:[
          { required: true, message: t('part.tips32')}
        ]
      }
      
    }
  },
  computed: {
    // TODO: 支持小数 提示
    minVariation () {
      let initData = this.initData;
      return !initData || !initData.precision ? 1 : (initData.precision == 1 ? 0.1 : 0.01);
    },
  },
  methods: {
    remove(row){
      let index = -1;
      for(let i = 0; i < this.form.length; i++){
        if(this.form[i] == row){
          index = i;
          break;
        }
      }

      if(index >= 0) this.form.splice(index, 1);
    },
    add(row = {}){
      if (this.form.length > 99) {
        return this.$message({
          showClose: true,
          message: t('task.tip.addSparePartTip2', {max:100}),
          type: 'error'
        });
      }

      let config = this.sparepartConfig || {};
      let types = config.outStoreType || [];

      let repertory = row.repertory || {};
      let sparepart = row.sparepart || {};

      if (this.form.length) {
        this.form.push({
          id: row.id,
          sparepart: sparepart.id || '',
          sparepartName: sparepart.name || '',
          serialNumber: sparepart.serialNumber || '',
          sparepartType: sparepart.type || '',
          standard: sparepart.standard || '',
          repertory: repertory.name || '',
          repertoryId: repertory.id || '',
          type: this.form[this.form.length - 1].type,
          repertoryCount: row.repertoryCount,
          safetyStock: row.safetyStock || null,
          variation: 1
        })
        return
      }
      this.form.push({
        id: row.id,
        sparepart: sparepart.id || '',
        sparepartName: sparepart.name || '',
        serialNumber: sparepart.serialNumber || '',
        sparepartType: sparepart.type || '',
        standard: sparepart.standard || '',
        repertory: repertory.name || '',
        repertoryId: repertory.id || '',
        type: types[0],
        repertoryCount: row.repertoryCount,
        safetyStock: row.safetyStock || null,
        variation: 1
      })
    },
    hasRow(row){
      return this.form.some(item => item.id == row.id)
    },
    fetchSparepart(keyword, cb){
      let repertoryIds = this.repertoryId ? {repertoryId: this.repertoryId} : {}
      let model = {
        keyWord: keyword,
        pageSize: 50,
        pageNum: 1,
        enable: 1,
        managers: [this.userId],
        ...repertoryIds
      }

      this.$http.post('/partV2/repertory/list', model)
        .then(result => {
          result.list = result.list.map(item => {
            //showArrow:判断箭头是否显示
            return {...item, 'showDetail':false, 'showArrow':item.sparepart.description ? true : false}
          })
          cb(result.list);
        })
        .catch(err => console.log(err))
    },
    choosePart(value, row){
      if(this.hasRow(value)) {
        this.$platform.toast('该记录已存在！', 'warning');
        return
      }

      row.id = value.id;
      row.sparepart = value.sparepart.id;
      row.sparepartName = value.sparepart.name;
      row.serialNumber = value.sparepart.serialNumber;
      row.sparepartType = value.sparepart.type;
      row.standard = value.sparepart.standard;
      row.repertory = value.repertory.name;
      row.repertoryId = value.repertory.id;
      row.repertoryCount = value.repertoryCount;
      row.safetyStock = value.safetyStock || null;
    },
    async pack(){
      let form = this.form;
      try {
        let message = '';
        let initData = this.initData;
        form.forEach((item, index) => {
          let count = this.decimalNumber(item.variation);
          if(!item.sparepart || !item.repertory || !item.type || !item.variation || item.variation > item.repertoryCount || item.variation <= 0 || count != -1){
            message = `${t('part.tips50')}${t('part.tips60')}`;
            message += initData.precision == 0
              ? t('common.form.preview.materialOrder.tip6')
              : t('part.tips51', {num:initData.precision});
          }
        })

        if(message){
          this.$platform.alert(message)
          return null;
        } 

        return form.map(item => ({
          sparepart: {
            id: item.sparepart,
          },
          repertory: {
            id: item.repertoryId
          },
          item: item.type,
          type: '出库',
          variation: -item.variation,
          remark: this.remark
        }));
      } catch (error) {
        console.log(error)
      }
      return null;
    },
    receive(data = [], userId = ''){
      if (data.length > 20) {
        return this.$platform.alert(t('part.tips61', {num:20}));
      }

      data.forEach(item => this.add(item));

      this.userId = userId;
    },
    decimalNumber(num) {
      let initData = this.initData;
      let count = MathUtil.decimalNumber(num);
      let isPartV2 = initData.isSparepart2;

      if(!isPartV2 && count != 0) return 0;
      if(initData.precision >= count) return -1;
      return initData.precision;
    }
  }
}
</script>

<style lang="scss">
.el-form-item{
  margin-bottom: 0
}

.part-batchIn-form{
  td,th{
    padding: 5px 0;
  }
  .cell {
    padding: 0 5px;
  }
}

.part-batchIn-footer{
  padding-top: 10px;
  text-align: center;
}

.batch-in-part{
  width: auto !important;
  max-width: 914px !important;
   
  li{
    padding: 5px;
    margin: 0 10px;
    border-bottom: 1px solid #f0f0f0;
    overflow: hidden;

    &:last-child{
      border-color: transparent;
    }
  }
}

.bacth-in-part-item{

  p{
    width:100%;
    overflow: hidden;
    white-space: initial;
    text-overflow: ellipsis;
    line-height: 24px;
    margin: 0;
  }
  .item-more {
     display: flex;
     line-height: 24px;
     .item-more-info {
       flex-grow: 1;
       padding-right: 16px;
     }
   }
}

.out-stock-remark{
  width:100%;
  display:flex;
  margin:10px 0 0;
  padding:0 5px;
  textarea{
    flex:1;
    height:40px;
    min-height:40px;
    padding:10px;
    border-color:#dadada;
    &:focus{
      outline: none;
      border-color: $color-primary;
    }  
  }     
}
</style>